<template>
  <div class="main">
    <Field
      type="text"
      label="联系人"
      placeholder="您的姓名"
      @change="(v) => this.address.contact_name = v"
      :value="this.address.contact_name"
    />
    <Field label type="radio" @sexChange="handleSexChange" :value="this.address.sex"/>
    <Field
      type="text"
      label="手机号"
      placeholder="配送员联系您的号码"
      @change="(v) => this.address.contact_mobile = v"
      :value="this.address.contact_mobile"
    />
    <Field type="custom" label="收货地址" placeholder="请选择省/市/区" :value="this.address.sex">
      <span @click="selectArea" class="area">{{address.area ? address.area : '请选择省/市/区'}}</span>
    </Field>
    <Field
      type="text"
      label="门牌号"
      placeholder="详细地址，例：1号楼一单元101室"
      @change="(v) => this.address.street = v"
      :value="this.address.street"
    />
    <template v-if="canDel">
      <Field type="del" label="删除该地址" @click.native="handleDeleteAddress"/>
    </template>
    <template v-if="canReturn">
      <Field type="return" label="退还水桶" @click.native="handleReturn"/>
    </template>
    <van-popup position="bottom" v-model="showArea">
      <van-picker
        ref="areaPick"
        :columns="columns"
        show-toolbar
        title="选择城市"
        @cancel="onCancel"
        @confirm="onConfirm"
        @change="onChange"
        value-key="name"
      />
    </van-popup>
    <ActionButton class="blue-btn" text="保存" @click="handleSubmit"/>
  </div>
</template>

<script>
import api from "../../api";
import common from "../../api/common";
import Field from "@/components/buyrecord/Field";
import ActionButton from "@/components/common/ActionButton";

import { Picker } from "vant";

const IsPhone = /^1[345789]\d{9}$/;

function AddressItem(code, name) {
  this.code = code;
  this.name = name;
}

AddressItem.prototype.toString = function() {
  return this.name;
};

let title = common.getParam("id") ? "新增地址" : "编辑地址";
export default {
  title: title,
  components: {
    Field,
    ActionButton
  },
  data() {
    return {
      uid: this.$store.state.uid,
      showArea: false,
      canDel: false,
      canReturn: false,
      areaList: {
        province_list: {},
        city_list: {},
        county_list: {}
      },
      deposit: this.$store.state.deposit,
      address: {
        id: common.getParam("id"),
        ids: [],
        contact_name: "",
        sex: "",
        contact_mobile: "",
        area: "",
        street: ""
      },
      mode: common.getParam("mode"),
      productId: common.getParam("productId"),
      number: common.getParam("number"),
      columns: [
        {
          values: [],
          className: "column1"
        },
        {
          values: [],
          className: "column2"
        },
        {
          values: [],
          className: "column3"
        }
      ],
      money: null
    };
  },
  methods: {
    handleReturn() {
      this.$routerPush(
        this,
        `/pages/station/Index?addressId=${this.address.id}&type=return`
      );
    },
    getAllAddress() {
      // 获取所有省
      api.address.getAllAddress(
        "",
        0,
        res => {
          this.columns[0].values = [];
          for (var code in res.province) {
            var name = res.province[code];
            this.columns[0].values.push(new AddressItem(code, name));
          }
          api.address.getAllAddress(
            this.columns[0].values[0].code,
            1,
            res => {
              this.columns[1].values = [];
              for (var code in res.city) {
                var name = res.city[code];
                this.columns[1].values.push(new AddressItem(code, name));
              }
              api.address.getAllAddress(
                this.columns[1].values[0].code,
                2,
                res => {
                  this.columns[2].values = [];
                  for (var code in res.dist) {
                    var name = res.dist[code];
                    this.columns[2].values.push(new AddressItem(code, name));
                  }
                },
                error => {
                  this.$toast(error.msg);
                }
              );
            },
            error => {
              this.$toast(error.msg);
            }
          );
        },
        error => {
          this.$toast(error.msg);
        }
      );
    },
    handleSexChange(v) {
      console.log(v);
      this.address.sex = v;
    },
    selectArea() {
      this.showArea = true;
    },
    onCancel() {
      this.showArea = false;
    },
    onConfirm() {
      var address = this.$refs.areaPick.getValues();
      var ids = [];
      var area = "";
      for (var c in address) {
        if (address[c] && typeof address[c] == "object") {
          area += address[c].name + "-";
          ids.push(address[c].code);
        }
      }
      area = area.substring(0, area.length - 1);
      this.address.area = area;
      this.address.ids = ids;
      this.showArea = false;
    },
    onChange(picker, values, index) {
      console.log("onChange: " + index);
      if (index == 0) {
        // 选择第一列
        var provincesId = this.$refs.areaPick.getColumnValue(0).code;
        api.address.getAllAddress(
          provincesId,
          1,
          res => {
            console.log(res);
            var city = [];
            for (var code in res.city) {
              var name = res.city[code];
              city.push(new AddressItem(code, name));
            }
            picker.setColumnValues(1, city);
            var cityId = city[0].code;
            api.address.getAllAddress(
              cityId,
              2,
              res => {
                var area = [];
                for (var code in res.dist) {
                  var name = res.dist[code];
                  area.push(new AddressItem(code, name));
                }

                picker.setColumnValues(2, area);
              },
              error => {
                this.$toast(error.msg);
              }
            );
          },
          error => {
            this.$toast(error.msg);
          }
        );
      } else if (index == 1) {
        // 选择第二列
        var cityId = this.$refs.areaPick.getColumnValue(1).code;
        api.address.getAllAddress(
          cityId,
          2,
          res => {
            var area = [];
            for (var code in res.dist) {
              var name = res.dist[code];
              area.push(new AddressItem(code, name));
            }

            picker.setColumnValues(2, area);
          },
          error => {
            this.$toast(error.msg);
          }
        );
      }
    },
    handleSubmit() {
      if (this.address.contact_name == "") {
        this.$toast(`请输入您的姓名`);
        return;
      }
      if (this.address.sex == "") {
        this.$toast(`请选择您的性别`);
        return;
      }
      if (this.address.contact_mobile == "") {
        this.$toast(`请输入您的手机号码`);
        return;
      }
      if (!IsPhone.test(this.address.contact_mobile)) {
        this.$toast(`请输入正确的手机号码`);
        return;
      }
      if (this.address.area == "") {
        this.$toast(`请选择地址`);
        return;
      }
      if (this.address.street == "") {
        this.$toast(`请输入详细地址`);
        return;
      }
      let id = this.address.id;
      let uid = this.uid;
      let contact_name = this.address.contact_name;
      let contact_mobile = this.address.contact_mobile;
      let sex = this.address.sex;
      let province_id = this.address.ids[0];
      let city_id = this.address.ids[1];
      let dist_id = this.address.ids[2];
      let street = this.address.street;
      let that = this;
      api.address.setUserAddress(
        id,
        uid,
        contact_name,
        contact_mobile,
        sex,
        province_id,
        city_id,
        dist_id,
        street,
        res => {
          if (that.money) {
            this.$toast.success({
              message: `保存成功`,
              duration: 2000,
              position: "middle",
              onClose() {
                that.$routerPush(that, `/pages/address/Index`)
              },
            })
          } else {
            this.$dialog
              .confirm({
                title: `提示`,
                message: `地址保存成功，是否缴纳押金？该地址押金${
                  this.deposit
                }元`
              })
              .then(() => {
                // 点击确定
                // this.$toast("缴纳押金...");

                // 点击确定
                var uid = this.$store.state.uid;
                var address_id = res.address_id;

                api.order.placeOrderForYa(uid, address_id, res => {
                  res = JSON.parse(res);
                  var timeStamp = res.timeStamp;
                  var nonceStr = res.nonceStr;
                  var packArr = res.package.split("=");
                  var paySign = res.paySign;
                  var total_fee = common.getParam("total");
                  var wxpackage = packArr[1];
                  var payType = "deposit";

                  //点击微信支付后，调取统一下单接口生成微信小程序支付需要的支付参数
                  var params = `?timeStamp=${timeStamp}&nonceStr=${nonceStr}&package=${wxpackage}&paySign=${paySign}&payType=${payType}`;

                  //定义path 与小程序的支付页面的路径相对应
                  var path = "/pages/wxpay/wxpay" + params;
                  //通过JSSDK的api使小程序跳转到指定的小程序页面
                  wx.miniProgram.navigateTo({ url: path });
                });
              })
              .catch(() => {
                // 点击取消
                if (this.mode) {
                  this.$routerPush(
                    this,
                    `/pages/address/Index?mode=${this.mode}&productId=${
                      this.productId
                    }&number=${number}`
                  );
                } else {
                  this.$routerPush(this, `/pages/address/Index`);
                }
              });
          }
        }
      );
    },
    loadBackAddressInfo() {
      if (!this.address.id) {
        return;
      }
      api.address.getAddressDetail(this.uid, this.address.id, res => {
        this.address.contact_name = res.contact_name;
        this.address.sex = String(res.sex);
        this.address.contact_mobile = res.contact_mobile;
        this.address.area = `${res.province_name}-${res.city_name}-${
          res.dist_name
        }`;
        this.address.street = res.street;
        if (res.money) {
          this.canReturn = true;
        } else {
          this.canDel = true;
        }
        this.money = res.money
        this.address.ids = [
          `${res.province_id}`,
          `${res.city_id}`,
          `${res.dist_id}`
        ];
      });
    },
    handleDeleteAddress() {
      this.$dialog
        .confirm({
          title: `提示`,
          message: `是否删除当前地址`
        })
        .then(() => {
          // 点击确定
          api.address.delUserAddress(this.address.id, this.uid, res => {
            let that = this;
            this.$toast.success({
              message: `删除成功`,
              position: "middle",
              onClose() {
                that.$routerPush(that, `/pages/address/Index`);
              }
            });
          });
        })
        .catch(() => {
          // 点击取消
        });
    }
  },
  created() {
    this.loadBackAddressInfo();
  },
  mounted() {
    this.getAllAddress();
  }
};
</script>

<style lang="less" scoped>
.main {
  width: 92vw;
  margin: 2vw auto;
  padding: 0 3vw;
  background: #fff;
  .area {
    display: inline-block;
    font-size: 4vw;
    width: 70vw;
    color: #999;
  }
}
</style>